<script setup lang="ts">
// 生意参谋 竞争 品牌识别 趋势分析

import moment from "moment";
import EChart from "~/contentScripts/views/echart.vue";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import Trans from "~/utils/sycm/trans";

const loginVisible = ref<Boolean>(false);
const visible = ref<Boolean>(false);
const date = ref<String>('');
const showZs = ref<Boolean>(false);
const data = ref<any>({
  // 客群指数 可转换为 支付买家数
  payByrCntIndex: [],
  // 支付转化指数 可转换为 支付转化率
  payRateIndex: [],
  // 交易指数 可转换为 交易金额
  tradeIndex: [],
  // 流量指数 可转换为 访客数
  uvIndex: [],
  // 支付转化率
  payRate: [],
  // 访客数
  uv: [],
  // 客单价
  price: [],
  // UV价值
  uvPrice: [],
});
const columns = ref<any[]>([]);
const calcColumns = () => {
  columns.value = [
    {
      dataIndex: 'brand',
      title: '品牌名称',
      dataType: 'brand',
      dataField: {
        brand_name: 'brand.brand_title',
        brand_logo: 'brand.brand_logo',
        // brand_url:'brand.brand_url',
      }
    },
    {
      dataIndex: 'date',
      title: '日期',
      sorter: (a: any, b: any) => a.date.localeCompare(b.date),
    },
    {
      dataIndex: 'tradeIndex',
      title: showZs.value ? '交易指数' : '交易金额',
      sorter: (a: any, b: any) => a.tradeIndex - b.tradeIndex,
      align: 'right',
      dataType: 'customRender',
      render: (text: any) => {
        if (showZs.value) {
          return text
        } else {
          const price = Trans.number(text);
          return (price + '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
      }
    },
    {
      dataIndex: 'uvIndex',
      title: showZs.value ? '流量指数' : '访客数',
      sorter: (a: any, b: any) => a.uvIndex - b.uvIndex,
      align: 'right',
      dataType: 'customRender',
      render: (text: any) => {
        if (showZs.value) {
          return text
        } else {
          const price = Trans.number(text);
          return (price + '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
      }
    },
    {
      dataIndex: 'payByrCntIndex',
      title: showZs.value ? '客群指数' : '支付买家数',
      sorter: (a: any, b: any) => a.payByrCntIndex - b.payByrCntIndex,
      align: 'right',
      dataType: 'customRender',
      render: (text: any) => {
        if (showZs.value) {
          return text
        } else {
          const price = Trans.number(text);
          return (price + '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
      }
    },
    {
      dataIndex: 'payRateIndex',
      title: showZs.value ? '支付转化指数' : '支付转化率',
      sorter: (a: any, b: any) => a.payRateIndex - b.payRateIndex,
      align: 'right',
      dataType: 'customRender',
      render: (text: any) => {
        if (showZs.value) {
          return text
        } else {
          return Trans.ratio(text);
        }
      }
    },
    {
      dataIndex: 'price',
      title: '客单价',
      sorter: (a: any, b: any) => a.price - b.price,
      align: 'right',
    },
    {
      dataIndex: 'uvPrice',
      title: 'UV价值',
      sorter: (a: any, b: any) => a.uvPrice - b.uvPrice,
      align: 'right',
    }
  ]
}
const dataSource = ref<any[]>([]);
const calcDataSource = (brand: any) => {
  const arr: any[] = [];
  data.value.payByrCntIndex.map((item: number, index: number) => {
    arr.push({
      brand: {
        brand_title: brand.name,
        brand_logo: brand.imgUrl.replaceAll('_48x48.jpg','').replaceAll('//img.alicdn.com/tps/',''),
        // brand_url: brand.brandUrl,
        b2Cbrand: brand.sellerType !== 'taobao',
      },
      date: moment(date.value).subtract(30 - (index + 1), 'day').format('YYYY-MM-DD'),
      tradeIndex: data.value.tradeIndex[index],
      payByrCntIndex: data.value.payByrCntIndex[index],
      payRateIndex: data.value.payRateIndex[index],
      payConvRate: Trans.ratio(data.value.payRateIndex[index]).replaceAll('%', ''),
      uvIndex: data.value.uvIndex[index],
      visitor: data.value.uv[index],
      price: data.value.price[index],
      uvPrice: data.value.uvPrice[index],
    })
  })
  dataSource.value = arr.reverse();
};
const echartOptions = ref({});
const calcEchartOptions = () => {
  echartOptions.value = {
    tooltip: {
      trigger: 'axis'
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片',
          name: '竞争-品牌识别-趋势分析',
          excludeComponents: ['toolbox'],
          pixelRatio: 2,
        }
      }
    },
    legend: {
      data: [
        showZs.value ? '交易指数' : '交易金额',
        showZs.value ? '流量指数' : '访客数',
        showZs.value ? '客群指数' : '支付买家数',
        showZs.value ? '支付转化指数' : '支付转化率',
        '客单价',
        'UV价值',
      ]
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.value.payByrCntIndex.map((item: any, index: number) => {
        return moment(date.value).subtract(30 - (index + 1), 'day').format('YYYY-MM-DD');
      }),
    },
    yAxis: [
      {
        category: 'value',
      },
      {
        category: 'value',
        axisTick: {
          show: false, // 隐藏刻度线
        },
        axisLabel: {
          show: false, // 隐藏标签
        },
        show: false,
      },
      {
        category: 'value',
        axisTick: {
          show: false, // 隐藏刻度线
        },
        axisLabel: {
          show: false, // 隐藏标签
        },
        show: false,
      },
      {
        category: 'value',
        axisTick: {
          show: false, // 隐藏刻度线
        },
        axisLabel: {
          show: false, // 隐藏标签
        },
        show: false,
      },
      {
        category: 'value',
        axisTick: {
          show: false, // 隐藏刻度线
        },
        axisLabel: {
          show: false, // 隐藏标签
        },
        show: false,
      },
      {
        category: 'value',
        axisTick: {
          show: false, // 隐藏刻度线
        },
        axisLabel: {
          show: false, // 隐藏标签
        },
        show: false,
      },
    ],
    series: [
      {
        name: showZs.value ? '交易指数' : '交易金额',
        type: 'line',
        yAxisIndex: 0,
        data: data.value.tradeIndex.map((item) => {
          if (showZs.value) {
            return item;
          } else {
            return Trans.number(item);
          }
        }),
        smooth: true,
      },
      {
        name: showZs.value ? '流量指数' : '访客数',
        type: 'line',
        yAxisIndex: 1,
        data: data.value.uvIndex.map((item) => {
          if (showZs.value) {
            return item;
          } else {
            return Trans.number(item);
          }
        }),
        smooth: true,
      },
      {
        name: showZs.value ? '客群指数' : '支付买家数',
        type: 'line',
        yAxisIndex: 2,
        data: data.value.payByrCntIndex.map((item) => {
          if (showZs.value) {
            return item;
          } else {
            return Trans.number(item);
          }
        }),
        smooth: true,
      },
      {
        name: showZs.value ? '支付转化指数' : '支付转化率',
        type: 'line',
        yAxisIndex: 3,
        data: data.value.payRateIndex.map((item) => {
          if (showZs.value) {
            return item;
          } else {
            return Trans.ratio(item).replaceAll('%', '');
          }
        }),
        smooth: true,
      },
      {
        name: '客单价',
        type: 'line',
        yAxisIndex: 4,
        data: data.value.price,
        smooth: true,
      },
      {
        name: 'UV价值',
        type: 'line',
        yAxisIndex: 5,
        data: data.value.uvPrice,
        smooth: true,
      },
    ]
  };
  console.log(echartOptions);
}

const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    }
  }, __option)) {
    //date 格式 2023-11-22
    date.value = document.querySelector("div.oui-date-picker-current-date")?.innerHTML.replaceAll('统计时间 ', '');
    const s = await SYCM.getInternalFiberData('[id^=op-mc-rival-trend-analysis] > div > div.op-mc-rival-trend-analysis-info div.op-mc-rival-trend-analysis-rival-object', 'pendingProps.children.props');
    console.log('s', s);
    const d = await SYCM.getInternalFiberData('[id^=op-mc-rival-trend-analysis] > div > div.op-mc-rival-trend-analysis-chart-container .oui-pro-composed-chart', 'memoizedProps.children._owner.memoizedProps.data');
    data.value.payByrCntIndex = d.payByrCntIndex;
    data.value.payRateIndex = d.payRateIndex;
    data.value.tradeIndex = d.tradeIndex;
    data.value.uvIndex = d.uvIndex;
    // 计算客单价
    data.value.price = d.tradeIndex.map((item: number, index: number) => {
      if (item === 0) {
        return 0;
      } else {
        return (Trans.number(item) / Trans.number(d.payByrCntIndex[index])).toFixed(2);
      }
    });
    data.value.uv = d.uvIndex.map((item: number, index: number) => {
      return Trans.number(item);
    });
    // 计算UV价值
    data.value.uvPrice = d.tradeIndex.map((item: number, index: number) => {
      if (item === 0) {
        return 0;
      } else {
        return (Trans.number(item) / Trans.number(d.uvIndex[index])).toFixed(2);
      }
    })
    // 计算支付转化率
    data.value.payRate = d.payRateIndex.map((item: number, index: number) => {
      return Trans.ratio(item).replaceAll('%', '');
    })
    calcColumns();
    calcEchartOptions();
    calcDataSource(s);
    console.log('d', data.value);
    visible.value = true;
  }
}
watch(() => showZs.value, () => {
  calcEchartOptions();
  calcColumns();
});
</script>

<template>
  <base-app>
    <a-button-group>
      <user style="margin-right: 0;"/>
      <a-button type="primary" size="small" @click="handle">
        一键转化
      </a-button>
    </a-button-group>
    <user-login-modal v-model:login-visible="loginVisible"/>
    <custom-modal title="竞争-品牌识别-趋势分析" width="95%" style="top: 20px" v-model:open="visible">
      <template #headerRight>
        <SYCMCustomModalHeaderNotice/>
        <a-checkbox style="margin-left: 10px;" v-model:checked="showZs">显示指数</a-checkbox>
      </template>

      <div style="height: calc(100vh - 150px); overflow-y: scroll;">
        <EChart :options="echartOptions" style="height: 300px;"/>
        <a-divider/>
        <base-table table-name="竞争-品牌识别-趋势分析" :data-source="dataSource" :columns="columns" :scroll="{
    y:450
  }"
        >

        </base-table>
      </div>
    </custom-modal>
  </base-app>
</template>

<style scoped>

</style>
